package icu.groot.alan.servlet.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import icu.groot.alan.entity.OneselfUser;
import icu.groot.alan.entity.TokenEntity;
import icu.groot.alan.service.UserService;
import icu.groot.alan.service.impl.UserServiceImpl;
import icu.groot.alan.util.R;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/oneself.do")
public class OneselfServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取token解析的实体类
        TokenEntity  tokenEntity = (TokenEntity) req.getAttribute("tokenEntity");
        req.removeAttribute("tokenEntity");

        UserService userService = new UserServiceImpl();
        OneselfUser oneself = userService.oneself(tokenEntity);
        if (oneself == null){
            resp.getWriter().print(new ObjectMapper().writeValueAsString(R.error("信息错误，请重新登录")));
        }else {
            req.getSession().setAttribute("oneself", oneself);
            req.getSession().setAttribute("navActive", "navOneself");
            req.getRequestDispatcher("/oneself.jsp").forward(req,resp);
        }
    }
}
